import threading
import time

'''python并发: https://blog.51cto.com/u_16213565/7504093'''

lock = threading.Lock()

class Account:
    def __init__(self, balance):
        self.balance = balance

def draw(account, amount):
    '''取钱'''
    if account.balance > amount:
        # sleep 一定会导致线程上下文切换和阻塞
        time.sleep(1)
        print(threading.current_thread().name, '取钱成功')
        
        account.balance -= amount
        print(threading.current_thread().name, '余额', account.balance)
    else:
        print(threading.current_thread().name, '余额不足')

def draw_lock(account, amount):
    with lock:
        '''取钱'''
        if account.balance > amount:
            # sleep 一定会导致线程上下文切换和阻塞
            time.sleep(1)
            print(threading.current_thread().name, '取钱成功')
            
            account.balance -= amount
            print(threading.current_thread().name, '余额', account.balance)
        else:
            print(threading.current_thread().name, '余额不足')

if __name__ == '__main__':
    account = Account(1000)
    # 未加锁的线程出现上下文切换导致结果错误
    # thread_a = threading.Thread(name='thread-A', target=draw, args=(account, 600))
    # thread_b = threading.Thread(name='thread-B', target=draw, args=(account, 600))

    # thread_a.start()
    # thread_b.start()

    thread_a = threading.Thread(name='thread-A', target=draw_lock, args=(account, 600))
    thread_b = threading.Thread(name='thread-B', target=draw_lock, args=(account, 600))

    thread_a.start()
    thread_b.start()

